const redis = require('../lib/redisClient')
const svgCaptcha = require('svg-captcha')
const Joi=require('joi')
/**
 * 创建验证码
 * @param req
 * @param res
 */
const createCaptcha = (req, res) => {
  const captcha = svgCaptcha.create({ width: 100, height: 25, fontSize: 30 })
  //验证码数据保存到redis
  redis.set('captcha', captcha.text)

  res.type('svg')
  return res.sendSuccess(captcha.data)

}

/**
 * 对验证码进行验证
 */
const verifyCaptcha = (req,res) => {
  let schema = Joi.object({
    captcha: Joi.string()
      .alphanum()
      .length(4)
      .required(),
  })
  let { error } = schema.validate(req.body)
	console.log(req.body)

  if (error) {
    let details = error.details[0]
    let path = details.path[0]

    return res.sendError({ msg: details[Object.keys(details).find(() => details['path'][0] === path)] })
  }
  redis.get('captcha', (err,value)=>{
    if(err) return res.sendError(err)
    if (!value) return res.sendError('验证码无效')
    let captcha = req.body['captcha']
    if (captcha.toLowerCase()===value.toLowerCase()){
      redis.del('captcha')
      return res.sendSuccess(true,'验证码验证成功')
    }
    return res.sendError('错误的验证码')

  })
}

module.exports = {
  createCaptcha,
  verifyCaptcha
}
